<?php

namespace app\controller\api;

use app\base\BaseEncryptController;
use app\factory\Order as OrderFactory;
use app\factory\User as UserFacade;
use app\libs\Util;
use app\model\goods\GoodsTypeModel;
use app\model\order\OrderItemModel;
use app\model\order\OrderItemOutModel;
use app\model\order\OrderModel;
use think\Request;

/**
 * 小程序首页请求接口
 * Class Index
 * @package app\controller
 */
class Order extends BaseEncryptController
{
    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * 订单展示
     * @param Request $request
     * @return \think\response\Json
     */
    public function onOrderShow(Request $request)
    {
        $formData = $request->param();
        $userInfo = $this->currentUser;//登录信息
        $OrderFactory = new OrderFactory();
        $res = $OrderFactory->orderInfo($formData, $userInfo);
        return self::returnMsg($res);
    }

    /**
     * 生成订单
     * @param Request $request
     * @return \think\response\Json
     */
    public function onCreateOrder(Request $request)
    {
        $formData = $request->param();
        $userInfo = $this->currentUser;//登录信息
        $OrderFactory = new OrderFactory();
        $res = $OrderFactory->cearteOrder($formData, $userInfo);
        return self::returnMsg($res);
    }

    /**
     * 订单列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function getOrderList(Request $request)
    {
        $formData = $request->param();
        $userInfo = $this->currentUser;//登录信息
        $UserFacade = new UserFacade();
        $res = $UserFacade->orderList($formData, $userInfo);
        return self::returnMsg($res);
    }

    /**
     * 获取订单详情
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderDetail(Request $request)
    {
        $id = $request->param('id');
        $type = $request->param('type');
        $logistics_id = $request->param('logistics_id');
        if (empty($id)) {
            return self::returnMsg(991, "参数有误");
        }
        $userInfo = $this->currentUser;//登录信息
        $UserFacade = new UserFacade();
        $order = $UserFacade->orderDetail($id, $type, $userInfo['user_id'], $logistics_id);
        if (empty($order)) {
            return self::returnMsg(0, "订单不存在");
        }
        return self::returnMsg(1, $order, '获取成功');
    }

    /**
     * 取消订单
     * @param Request $request
     * @return \think\response\Json
     */
    public function onCancelOrder(Request $request)
    {
        $res['code'] = 0;
        $res['msg'] = "无权取消";
        $formData = $request->param();
        $userInfo = $this->currentUser;//登录信息
        $order_id = $formData['order_id'];
        $order_model = new OrderModel();
        $map = [
            'id' => $order_id,
            'user_id' => $userInfo['user_id'],
        ];
        $order_data = $order_model->where($map)->field('order_status,goods_type')->find();
        if (empty($order_data)) {
            $res['code'] = 10;
            $res['msg'] = "无权取消";
            return self::returnMsg($res);
        }
        if (intval($order_data['goods_type'])) {
            $res['code'] = 20;
            $res['msg'] = "取消失败";
            return self::returnMsg($res);
        }
        if (intval($order_data['order_status']) == 1) {
            $res = $order_model->cancelOrder($order_id, $userInfo['user_id']);
        } else if (intval($order_data['order_status']) == 2) {
            $retx = $order_model->refundOrder($order_id);
            if ($retx === false) {
                $res['code'] = 0;
                $res['msg'] = "退款失败";
                return self::returnMsg($res);
            }
            $order_item_model = new OrderItemModel();
            $ret = $order_item_model->cancelOrderStore($order_id);
            if ($ret === false) {
                $res['code'] = 0;
                $res['msg'] = "订单状态更新出错";
            } else {
                $res['code'] = 1;
                $res['msg'] = "取消订单退款成功";
            }
        }
        return self::returnMsg($res);
    }

    /**
     * 申请退款/退货
     * @param Request $request
     * @return \think\response\Json
     */
    public function onOutOrder(Request $request)
    {
        $formData = $request->param();
        $type = $formData['type'];
        $userInfo = $this->currentUser;//登录信息
        if ($type == 'repeal') {
            $order_item_out_model = new OrderItemOutModel();
            $res = $order_item_out_model->cancelOutOrder($formData['out_id'], $userInfo['user_id']);
        } else {
            $order_model = new OrderModel();
            $res = $order_model->outOrder($formData['order_id'], $formData['order_item_ids'], $formData['out_explain'], $userInfo['user_id']);
        }
        return self::returnMsg($res);
    }

    /**
     * 确认收货
     * @param Request $request
     * @return \think\response\Json
     */
    public function onConfirmTake(Request $request)
    {
        $formData = $request->param();
        $userInfo = $this->currentUser;//登录信息
        $order_model = new OrderModel();
        $res = $order_model->confirmTake($formData['order_id'], $userInfo['user_id']);
        return self::returnMsg($res);
    }

    /**
     * 订单物流
     * @param Request $request
     * @return \think\response\Json
     */
    public function onOrderLogistics(Request $request)
    {
        $formData = $request->param();
//        $userInfo = $this->currentUser;//登录信息
        $UserFacade = new UserFacade();
        $res = $UserFacade->orderLogistics($formData);
        return self::returnMsg($res);
    }

    /**
     * 用户设置物流
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function onOrderOutLogistics(Request $request)
    {
        $type = $request->param('type');
        $order_id = $request->param('order_id');
        $order_out_item_model = new OrderItemOutModel();
        $formData = [
            "order_id" => $order_id,
            "logistics_name" => $request->param("name"),
            "logistics_number" => $request->param("number")
        ];
        $logistics = [
            'name' => $formData['logistics_name'],
            'number' => $formData['logistics_number']
        ];
        $res = $order_out_item_model->setLogistics($order_id, $logistics, $type);
        return self::returnMsg($res);
    }

    /**
     * 获取购买消费情况统计数据
     * @param Request $request
     * @return \think\response\Json
     */
    public function getOrderStatistics(Request $request)
    {
        $type = $request->param('type');//0 时间区间，1三天 2七天 3十五天 4三十天
        $order_item_model = new OrderItemModel();
        $map = [
            'user_id' => $this->currentUser['user_id']
        ];
        $field = "a.user_id,a.goods_id,a.order_total,sum(a.order_total) as all_total,b.goods_first_id";
//        $field = "a.user_id,a.goods_id,a.order_total,b.goods_first_id";
        if (!empty($type)) {
            $time_start = date("Y-m-d", time() - (3600 * 24 * 3));
            switch ($type) {
                case 1:
                    $time_start = date("Y-m-d", time() - (3600 * 24 * 3));
                    break;
                case 2:
                    $time_start = date("Y-m-d", time() - (3600 * 24 * 7));
                    break;
                case 3:
                    $time_start = date("Y-m-d", time() - (3600 * 24 * 15));
                    break;
                case 4:
                    $time_start = date("Y-m-d", time() - (3600 * 24 * 30));
                    break;
            }
            $time_end = time();
            $time_start = strtotime($time_start);
            $time = [$time_start, $time_end];
            $order_item_list = $order_item_model->alias('a')->join("t_goods b", "a.goods_id=b.id")->where('a.order_status', '>', 1)->where($map)->createTime($time)->field($field)->group("b.goods_first_id")->select();
//            $order_item_list = $order_item_model->alias('a')->join("t_goods b", "a.goods_id=b.id")->where('a.order_status', '>', 1)->where($map)->createTime($time)->field($field)->select();
        } else {
            $time_start = $request->param('time_start');
            $time_end = $request->param('time_end');
            if (empty($time_start)) {
                $time_start = date("Y-m-d", time() - (3600 * 24 * 15));
            }
            if (empty($time_end)) {
                $time_start = date("Y-m-d");
            }
            $time_start = strtotime($time_start);
            $time_end = strtotime($time_end);
            $time = [$time_start, $time_end];
            $order_item_list = $order_item_model->alias('a')->join("t_goods b", "a.goods_id=b.id")->where('a.order_status', '>', 1)->where($map)->createTime($time)->field($field)->group("b.goods_first_id")->select();
        }

        $all_total = 0;
        foreach ($order_item_list as $key => $value) {
            $all_total += $value['all_total'];
        }
        $all_total = round($all_total, 2);
        $order_first_lists = [];
        foreach ($order_item_list as $key => $value) {
            $order_first_lists[] = [
                'list' => $value,
                'name' => GoodsTypeModel::getTypeName($key),
                'total' => round($value['all_total'], 2),
                'all_total' => $all_total,
                'rate' => round(($value['all_total'] / $all_total) * 100, 2)
            ];
        }
        Util::listOrder($order_first_lists, 'total', 'desc');
        $data = [
            'all_total' => $all_total,
            'list' => $order_first_lists
        ];
        $res = [
            'code' => 1,
            'data' => $data,
            'msg' => "获取成功"
        ];
        return self::returnMsg($res);
    }
}
